﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;

namespace BoriPeter.NutritionManager.FatSecret
{
    public class FoodsSearchMessage : MessageBase
    {
        private const string METHOD_VALUE = "foods.search";
        private const string SEARCH_EXPRESSION = "search_expression";
        private const string PAGE_NUMBER = "page_number";

        public async Task<FoodsSearchModel> SendAsync()
        {
            var response = await SendDataAsync(RequestUrl);
            System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( response));
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(mStream);
            using (var reader = new XmlTextReader(@"e:\foodssearch.xsd"))
            {
                var sch = XmlSchema.Read(reader, xmlValidationEventHandler);
                xmlDoc.Schemas.Add(sch);
                xmlDoc.Validate(xmlValidationEventHandler);
            }

            var messageModel = XmlDeserializeFromString<FoodsSearchModel>(response);

            return messageModel;
        }

        private void xmlValidationEventHandler(object sender, ValidationEventArgs e)
        {
            Debug.WriteLine(e.Message);
        }

        public FoodsSearchMessage(string searchExpression, int page)
            : base()
        {
            AddMessageParameter(METHOD, METHOD_VALUE);
            //AddMessageParameter(OAUTH_TOKEN, OAuthToken);
            AddMessageParameter(SEARCH_EXPRESSION, searchExpression);
            AddMessageParameter(PAGE_NUMBER, page.ToString());
        }
    }
}
